package com.huage.courseplatform.application.controller;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huage.courseplatform.application.model.dto.BusinessDTO;
import com.huage.courseplatform.application.model.dto.CourseDTO;
import com.huage.courseplatform.application.model.dto.TeacherDTO;
import com.huage.courseplatform.application.model.entity.Business;
import com.huage.courseplatform.application.model.entity.Course;
import com.huage.courseplatform.application.model.entity.Period;
import com.huage.courseplatform.application.model.entity.Teacher;
import com.huage.courseplatform.application.model.param.BusinessApplyPARAM;
import com.huage.courseplatform.application.model.param.CoursePARAM;
import com.huage.courseplatform.application.model.param.TeacherApplyPARAM;
import com.huage.courseplatform.application.model.vo.CoursePeriodVO;
import com.huage.courseplatform.application.service.ApplyAccountService;
import com.huage.courseplatform.application.service.BusinessService;
import com.huage.courseplatform.application.service.CourseService;
import com.huage.courseplatform.application.service.PeriodService;
import com.huage.courseplatform.framework.annotation.RepeatSubmit;
import com.huage.courseplatform.framework.api.AbstractController;
import com.huage.courseplatform.framework.api.BaseController;
import com.huage.courseplatform.framework.model.param.PagePARAM;
import com.huage.courseplatform.framework.utils.BeanCopyUtils;
import com.huage.courseplatform.framework.utils.ResultUtils;
import com.huage.courseplatform.satoken.model.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@RestController
@RequestMapping(value = "/course")
@Api(tags = "课程接口")
@Slf4j
@SaCheckRole({"ROLE_ADMIN","ROLE_BUSINESS"})
public class CourseController extends AbstractController<Course,CourseDTO,CoursePARAM> {


    @Resource
    CourseService courseService;


    @RepeatSubmit
    @ApiOperation(value = "添加（课程和课时）")
    @PostMapping(value = "/add")
    public ResultUtils<CoursePeriodVO> add(@RequestBody @Validated({Insert.class}) CoursePARAM coursePARAM) {
        Course course = this.paramToEntity(coursePARAM);
        courseService.addCourse(course,coursePARAM.getPeriodIdList());
        return ResultUtils.success(BeanCopyUtils.copyProperties(coursePARAM,CoursePeriodVO.class));
    }


    @RepeatSubmit
    @ApiOperation(value = "更新")
    @PutMapping(value = "/update")
    public ResultUtils<CourseDTO> update(@RequestBody @Validated({Update.class}) CoursePARAM coursePARAM) {
        Assert.isTrue(checkUserCourse(coursePARAM.getId()),"用户权限不足");
        Course course = this.paramToEntity(coursePARAM);
        courseService.updateCourse(course,coursePARAM.getPeriodIdList());
        return ResultUtils.success(entityToDto(course));
    }

    @SaIgnore
    @ApiOperation(value = "根据id查询课程和课时")
    @GetMapping(value = "/getCourseAndPeriodById/{id}")
    public ResultUtils<CoursePeriodVO> getCourseAndPeriodById(@PathVariable String id) {
        return ResultUtils.success(courseService.getCourseAndPeriodById(id));
    }



    @ApiOperation(value = "根据id删除")
    @DeleteMapping(value = "/delete/{id}")
    public ResultUtils<String> deleteById(@PathVariable String id) {
        Assert.isTrue(checkUserCourse(id),"用户权限不足");
        courseService.removeById(id);
        return ResultUtils.success(id);
    }

    @ApiOperation(value = "根据id集合删除")
    @DeleteMapping(value = "/delete")
    public ResultUtils<List<String>> deleteByIds(@RequestBody List<String> ids) {
        ids.forEach(id->{
            Assert.isTrue(checkUserCourse(id),"用户权限不足");
        });
        courseService.removeByIds(ids);
        return ResultUtils.success(ids);
    }

    //无缓存
    @SaIgnore
    @ApiOperation(value = "分页查询(无课时)")
    @PostMapping(value = "/page")
    public ResultUtils<Page<CourseDTO>> getByPage(@Validated @RequestBody PagePARAM pagePARAM){
        Page<CourseDTO> page = new Page(pagePARAM.getPageNum(),pagePARAM.getPageSize());
        QueryWrapper<CourseDTO> qw =  super.getQueryWrapperByPageParam(pagePARAM);
        return ResultUtils.success(courseService.coursePage(page,qw));
    }



    /**
     * 根据课程ID校验是否是当前用户商家拥有的课程
     * @param courseId
     * @return
     */
    private Boolean checkUserCourse(String courseId){
        if(!StpUtil.getRoleList().contains("ROLE_ADMIN")){
            //只允许修改本人
            String userId = (String) StpUtil.getLoginId();
            //获取该课程商家的用户id列表
            List<String> userIds = courseService.getUserIdListByCourseId(courseId);
            return userIds.contains(userId);
        }
        return true;

    }

}
